package java.socket_2;



import java.io.*;

import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Client {
    private Socket socket;
    public Client(){
        try {
            System.out.println("正在链接服务端");
            socket=new Socket("localhost",8088);
            System.out.println("成功链接到服务器");
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

    }
    public void start(){
        try {
            //低级输出流接入插座
            OutputStream os= socket.getOutputStream();
            //高级输入流编辑器链接低级输出流，并且规定编码UTF-8
            OutputStreamWriter osw=new OutputStreamWriter(os, StandardCharsets.UTF_8);
            //接入缓冲输出流
            BufferedWriter bw=new BufferedWriter(osw);
            //接入行刷新缓冲输出流
            PrintWriter pw=new PrintWriter(bw,true);
            //创建一个扫描器后面要用
            Scanner scn=new Scanner(System.in);
            while (true){//创建一个循环用于一直发送消息
                String line=scn.nextLine();//用一个字符串保存消息
                if ("exit".equalsIgnoreCase(line)){//加入退出条件
                    break;
                }
                pw.println(line);//通过的内容输出出去
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {

            try {
                //交互完毕断开链接
                socket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void main(String[] args) {
        //创建一个客户端
        Client client=new Client();
        //客户端开始运行
        client.start();

    }
}
